import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    numberArray: [],//选项
    chooseNum: null,
    value:null,//选择的值
    timeStr: 0,//页面倒计时
    count: 0,//题目数量
    currentIndex: 0, // 当前题目索引
    currentTopic: null, // 当前展示的题目
    imgFileArray: '', //选项图片文件
    imageUrl: '',//问题图片文件
    questionAnswer:null,//答案
    title:'',//标题
    questionIndex:0,//当前题型索引
    topicContent:[],//当前题型所有题目
    countdownInterval: null, // 添加倒计时定时器ID
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.getTopicData();
    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  
  getTopicData(){
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count,topicContent} = util.getData(questionIndex);
    this.setData({
      count,
      topicContent,
      questionIndex
    })
    this.getCurrentTopicData();
  },
  getCurrentTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {topicContent,currentIndex,count} = this.data;
    // 缓存下一题图片
    let newIndex = currentIndex + 1;
    if(newIndex < count){
      util.preLoadImg(questionIndex,newIndex)
    }
    
    const preImgs = wx.getStorageSync('preImgs')||[];

    const currentTopic = topicContent[currentIndex];// 当前展示的题目
    const questionContent = JSON.parse(currentTopic.answerSheet).content;// 问题描述
    const questionCountdown = JSON.parse(currentTopic.answerSheet).residenceTime;
    const timeStr = parseInt(questionCountdown, 10) / 1000;//题目停留时长
    const questionImgSrc = questionContent.match(/<img[^>]+src="([^">]+)"/);
    // const imageUrl = util.base_url + questionImgSrc[1];// 拼接图片
    let imageUrl = '';
    if (questionImgSrc && questionImgSrc[1]) {
      let imgSrc = questionImgSrc[1];
      // 判断是否已经包含完整的 URL（http 或 https）
      if (imgSrc.startsWith('http')) {
        imageUrl = imgSrc;
      } else {
        imageUrl = util.base_url + imgSrc;
      }
    }
    // 替换缓存图片
    const isIos =  util.checkPlatform()
    if(isIos){
      imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,jpg'
    }else{
      imageUrl = preImgs.find(item => item.url===imageUrl)?.path??imageUrl+'?x-oss-process=image/format,webp'
    }
    
    console.log('imageUrl,'+imageUrl)
    const numberArray = currentTopic.optionList;//选项
    const questionAnswer = currentTopic.questionAnswer;//答案
    const descArray = questionContent.match(/<p[^>]*>(.*?)<\/p>/i); // 得到标题数组
    const title = descArray[0];// 标题数据
    //选项图片文件
    const imgFileArray = numberArray.map((item) => {
      
      let fileUrl = '';
      if(item.fileUrl.startsWith('http')){
        fileUrl = item.fileUrl
      }else{
        fileUrl = util.base_url + item.fileUrl
      }
      const isIos =  util.checkPlatform()
      if(isIos){
        fileUrl = preImgs.find(itemImgs => itemImgs.url===fileUrl)?.path??fileUrl+'?x-oss-process=image/format,jpg'
      }else{
        fileUrl = preImgs.find(itemImgs => itemImgs.url===fileUrl)?.path??fileUrl+'?x-oss-process=image/format,webp'
      }
     
      console.log('fileUrl,'+fileUrl)
      return {
        fileUrl: fileUrl,
        serialNumber: item.serialNumber
      }
    })
    this.setData({
      currentTopic,
      numberArray,
      questionAnswer,
      title,
      timeStr,
      imageUrl,
      imgFileArray,
      questionStartTime: new Date().getTime(),
    }, () => {
    // 只在非首次加载时手动重置组件
      if (currentIndex > 0) {
        wx.nextTick(() => {
          const countdownTimer = this.selectComponent('#countdownTimer');
          if (countdownTimer) {
            countdownTimer.reset(timeStr);
          }
        });
      }
    });
  },
  onCountdownFinish() {
    // 倒计时结束，视为错误
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });
    const {count,currentIndex} = this.data;

    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(true);

    let totalCount = currentIndex + 1;
    this.setData({
      currentIndex:totalCount,
      answerRecords: newAnswerRecords
    })
   setTimeout( () =>{
    if (totalCount >= count) {
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);//跳转下一题
    } else {
      // 继续下一题
      this.setData({
        chooseNum: null,
        value:''
      })
      this.getCurrentTopicData();
    }
   },1000)
  },
  onChoose(e) {
    let index = e.currentTarget.dataset.index;
    let {numberArray} = this.data;
    let value = numberArray[index].serialNumber;
    this.setData({
      chooseNum: index,
      value
    })
  },
  // 提交
  onSubmit() {
    let {count,currentIndex,value} = this.data;
    this.setData({
      imageUrl: '',
      imgFileArray: []
    })
    if (!value) return;
    setTimeout(() => {
      // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value);
    let totalCount = currentIndex + 1;
    this.setData({
      currentIndex:totalCount,
      answerRecords: newAnswerRecords
    })
    if (totalCount >= count) {
      let questionNumber = this.data.questionIndex + 1;
      const prevInfo = wx.getStorageSync('questionInfo') || {};
      wx.setStorageSync('questionInfo', {
        ...prevInfo,
        questionNumber
      });
      util.navigateByDesc(questionNumber);//跳转下一题
    } else {
      // 继续下一题
      this.setData({
        chooseNum: null,
        value:''
      })
      this.getCurrentTopicData();
    }
    }, 0);
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '') {
    const {currentIndex, questionStartTime, topicContent, questionAnswer} = this.data;
    
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);
    
    // 获取当前题目信息
    const currentTopic = topicContent[currentIndex];
    
    // 判断是否正确（超时视为错误）
    let isRight = 0;
    let option = '';
    
    if (!isTimeout) {
      option = userOption;
      isRight = (userOption === questionAnswer) ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: currentTopic.questionId,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.classify,
      stem: currentTopic.stem,
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: currentTopic.questionAnswer,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
  }
});